import server_socket
from config import *
from socket_wrapper import SocketWrapper
from threading import Thread
from db import Db
from response_protocol import ResponseProtocol

class server():
    def __init__(self):
        self.server_socket = server_socket.ServerSocket()
        self.db = Db()
        #字典，存储格式为socket:username
        self.clients = dict()

    #服务器的主业务流程
    def run(self):
        while True:
            client_socket,sockaddr = self.server_socket.accept()
            print('客户端:',sockaddr,'已连接')
            t = Thread(target=self.request_handle,args=(client_socket,sockaddr))
            t.start()

    #客户端信息处理流程
    def request_handle(self,client_socket,sockaddr):
        client_socket = SocketWrapper(client_socket)
        while True:
            #接收客户端发来的信息
            data = client_socket.recv_data()
            if not data:
                self.remove_offline_user(client_socket)
                client_socket.close()
                print('客户端:', sockaddr, '已断开')
                break
            #client_socket.send_data('服务器已收到：'+data)
            #分析客户端信息：登录或者发送信息，分别交给不同的处理函数
            request_handle_func = dict()
            request_handle_func[REQUEST_CHAT] = self.request_chat_handle
            request_handle_func[REQUEST_LOGIN] = self.request_login_handle
            request_data = self.request_parse(data)
            handle_func = request_handle_func[request_data['request_id']]
            handle_func(request_data,client_socket)

    #删除不在线用户
    def remove_offline_user(self,client_socket):
        if client_socket in self.clients:
            del self.clients[client_socket]
        self.send_update_online()

    #解析发送的信息
    def request_parse(self,data):
        request_list = data.split('|')
        request_data = {}
        request_data['request_id'] = request_list[0]
        #登录聊天信息
        if request_data['request_id'] == REQUEST_LOGIN:
            request_data['username'] = request_list[1]
            request_data['password'] = request_list[2]
        #用户发送信息
        elif request_data['request_id'] == REQUEST_CHAT:
            request_data['username'] = request_list[1]
            request_data['messages'] = request_list[2]
        return request_data

    #登录信息处理函数
    def request_login_handle(self,request_data,client_socket):
        print(request_data['username'],request_data['password'])
        sql = "select * from users where user_name = '{}'".format(request_data['username'])
        result = self.db.get_one(sql)
        if result == None:
            data_to_send = ResponseProtocol.response_login_result('0',LOGIN_ERROR_NONEXISTENT,'','')
        elif request_data['password'] == result['user_password']:
            flag = self.isin_clients(result['user_name'])
            if flag == False:
                self.clients[client_socket] = result['user_name']
                self.send_update_online()
                onlineusers = self.get_onlineusers()
                data_to_send = ResponseProtocol.response_login_result('1', result['user_nickname'], result['user_name'],onlineusers)
            else:
                data_to_send = ResponseProtocol.response_login_result('0', LOGIN_ERROR_REPEAT, '', '')
        else:
            data_to_send = ResponseProtocol.response_login_result('0',LOGIN_ERROR_USERPWD,'','')
        client_socket.send_data(data_to_send)

    #客户端发送信息处理函数
    def request_chat_handle(self,request_data,client_socket):
        data_to_send = ResponseProtocol.response_chat(request_data['username'],request_data['messages'])
        print(data_to_send)
        for socket in self.clients:
            socket.send_data(data_to_send)

    #获得当前在线用户的信息
    def get_onlineusers(self):
        onlineusers = ''
        for key, value in self.clients.items():
            users = value + '\n'
            onlineusers += users
        return onlineusers

    #发送在线用户更新的信息
    def send_update_online(self):
        onlineusers = self.get_onlineusers()
        data_to_send = ResponseProtocol.response_update_online(onlineusers)
        for socket in self.clients:
            socket.send_data(data_to_send)

    #检查该用户是否已登录过
    def isin_clients(self,username):
        flag = False
        for key,value in self.clients.items():
            if value == username:
                flag = True
        return flag


if __name__ == '__main__':
    tcpServer = server()
    tcpServer.run()